<template>
  <div class="category-container">
    <!-- 分类标题 -->
    <div class="category-header">
      <h2>商品分类</h2>
    </div>

    <!-- 分类主体内容 -->
    <div class="category-main">
      <!-- 左侧一级分类 -->
      <div class="first-level">
        <ul>
          <li
              v-for="item in firstLevelCategories"
              :key="item.id"
              :class="{ active: activeFirstLevel === item.id }"
              @click="handleFirstLevelClick(item.id)"
          >
            {{ item.name }}
          </li>
        </ul>
      </div>

      <!-- 中间二级分类 -->
      <div class="second-level">
        <div v-if="secondLevelCategories.length > 0">
          <!-- 品牌展示区域 -->
          <div class="brand-section" v-if="currentBrands.length > 0">
            <h3>相关品牌</h3>
            <div class="brand-grid">
              <div
                  class="brand-item"
                  v-for="brand in currentBrands"
                  :key="brand.id"
                  @click="handleBrandClick(brand)"
              >
                <el-image
                    v-if="brand.logo"
                    :src="brand.logo"
                    fit="contain"
                    class="brand-logo"
                />
                <div class="brand-name">{{ brand.name }}</div>
              </div>
            </div>
          </div>

          <!-- 二级分类列表 -->
          <h3>二级分类</h3>
          <ul>
            <li
                v-for="item in secondLevelCategories"
                :key="item.id"
                :class="{ active: activeSecondLevel === item.id }"
                @click="handleSecondLevelClick(item)"
            >
              {{ item.name }}
              <!-- 三级分类下拉箭头 -->
              <el-icon
                  v-if="item.children && item.children.length > 0"
                  class="dropdown-icon"
                  :class="{ rotated: activeSecondLevel === item.id }"
              >
                <ArrowDown />
              </el-icon>
            </li>
          </ul>
        </div>
        <div v-else class="empty-tip">
          <el-empty description="暂无二级分类" />
        </div>
      </div>

      <!-- 右侧内容区域 - 修改为同时展示三级分类和商品 -->
      <div class="right-content">
        <!-- 三级分类区域 -->
        <div class="third-level">
          <div v-if="thirdLevelCategories.length > 0">
            <h3>{{ activeSecondLevelName }} - 三级分类</h3>
            <div class="third-level-grid">
              <el-link
                  v-for="sub in thirdLevelCategories"
                  :key="sub.id"
                  type="primary"
                  :underline="false"
                  @click="handleCategoryClick(sub)"
              >
                {{ sub.name }}
              </el-link>
            </div>
          </div>
          <div v-else class="empty-tip">
            <el-empty :description="activeSecondLevel ? '暂无三级分类' : '请先选择二级分类'" />
          </div>
        </div>

        <!-- 商品展示区域 -->
        <div class="product-section" v-if="products.length > 0">
          <h3>商品推荐</h3>
          <div class="product-grid">
            <div class="product-row" v-for="(row, index) in chunkedProducts" :key="index">
              <div
                  class="product-item"
                  v-for="product in row"
                  :key="product.id"
                  @click="handleProductClick(product)"
              >
                <el-image
                    :src="product.avatar"
                    fit="cover"
                    class="product-image"
                />
                <div class="product-info">
                  <div class="product-name">{{ product.productName }}</div>
                  <div class="product-price">¥{{ product.price }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'

// 响应式数据
const firstLevelCategories = ref([])
const secondLevelCategories = ref([])
const thirdLevelCategories = ref([])
const currentBrands = ref([])
const activeFirstLevel = ref(null)
const activeSecondLevel = ref(null)
const activeSecondLevelName = ref('')
const activeThirdLevel = ref(null) // 新增：当前选中的三级分类
const products = ref([])



// 计算属性 - 将商品数组分割为每行两个的二维数组
const chunkedProducts = computed(() => {
  const chunkSize = 2
  const result = []
  for (let i = 0; i < products.value.length; i += chunkSize) {
    result.push(products.value.slice(i, i + chunkSize))
  }
  return result
})

// 统一的请求错误处理函数
const handleRequestError = (error, messagePrefix) => {
  console.error(`${messagePrefix}失败:`, error)
  ElMessage.error(`${messagePrefix}失败: ${error.message}`)
}

// 获取一级分类
const fetchFirstLevelCategories = async () => {
  try {
    const response = await axios.get('/api/brand/brand/findCategoryById1')
    console.log('一级分类响应:', response.data)

    if (response.data?.code === 200) {
      firstLevelCategories.value = response.data.data || []

      if (firstLevelCategories.value.length > 0) {
        activeFirstLevel.value = firstLevelCategories.value[0].id
        await fetchSecondLevelCategories(activeFirstLevel.value)
      }
    } else {
      ElMessage.warning('获取一级分类失败: ' + (response.data?.message || ''))
    }
  } catch (error) {
    handleRequestError(error, '获取一级分类')
  }
}

// 获取二级分类
const fetchSecondLevelCategories = async (parentId) => {
  try {
    const id = Number(parentId)
    if (isNaN(id)) {
      throw new Error('无效的分类ID')
    }

    const response = await axios.get('/api/brand/brand/findCategoryById2', {
      params: {
        parentId: id
      }
    })

    if (response.data?.code === 200) {
      let data = response.data.data

      // 处理返回数据
      if (!data) {
        secondLevelCategories.value = []
      } else if (Array.isArray(data)) {
        secondLevelCategories.value = data
      } else {
        // 单个对象转为数组
        secondLevelCategories.value = [data]
        currentBrands.value = data.brands || []
      }

      // 重置三级分类和商品
      thirdLevelCategories.value = []
      products.value = []
      activeSecondLevel.value = null
      activeThirdLevel.value = null // 重置选中的三级分类

      // 默认选中第一个二级分类
      if (secondLevelCategories.value.length > 0) {
        handleSecondLevelClick(secondLevelCategories.value[0])
      }
    } else {
      ElMessage.warning(response.data?.message || '获取二级分类失败')
    }
  } catch (error) {
    handleRequestError(error, '获取二级分类')
  }
}

// 获取三级分类
const fetchThirdLevelCategories = async (parentId) => {
  try {
    console.log('正在获取三级分类，parentId:', parentId)
    const response = await axios.get('/api/brand/brand/findCategoryById3', {
      params: { parentId: parentId }
    })
    console.log('三级分类完整响应:', response.data) // 打印完整响应

    if (response.data?.code === 200) {
      // 修改这里，适配返回的数据结构
      thirdLevelCategories.value = response.data.data?.categories || []
      console.log('三级分类数据:', thirdLevelCategories.value)
    } else {
      ElMessage.warning('获取三级分类失败: ' + (response.data?.message || ''))
    }
  } catch (error) {
    handleRequestError(error, '获取三级分类')
  }
}

// 获取商品列表
const fetchProducts = async (brandId, categoryId) => {
  try {
    const response = await axios.get('/api/brand/brand/findProducts', {
      params: {
        brandId: brandId,
        categoryId: categoryId
      }
    })

    if (response.data?.code === 200) {
      products.value = response.data.data || []
    } else {
      ElMessage.warning('获取商品失败: ' + (response.data?.message || ''))
    }
  } catch (error) {
    handleRequestError(error, '获取商品')
  }
}

// 点击一级分类
const handleFirstLevelClick = async (id) => {
  if (activeFirstLevel.value === id) return
  activeFirstLevel.value = id
  await fetchSecondLevelCategories(id)
}

// 点击二级分类
const handleSecondLevelClick = async (item) => {
  if (activeSecondLevel.value === item.id) {
    activeSecondLevel.value = null
    thirdLevelCategories.value = []
    products.value = []
    activeThirdLevel.value = null // 重置选中的三级分类
    return
  }

  activeSecondLevel.value = item.id
  activeSecondLevelName.value = item.name

  // 如果有品牌数据，直接使用
  if (item.brands && item.brands.length > 0) {
    currentBrands.value = item.brands
    // 默认加载第一个品牌的商品
    if (item.brands.length > 0) {
      await fetchProducts(item.brands[0].id, null)
    }
  } else {
    currentBrands.value = []
    products.value = []
  }

  await fetchThirdLevelCategories(item.id)
}

// 点击品牌
const handleBrandClick = async (brand) => {
  console.log('点击品牌:', brand)
  // 加载该品牌和当前选中三级分类下的商品
  await fetchProducts(brand.id, activeThirdLevel.value)
}

// 点击分类项
const handleCategoryClick = async (category) => {
  console.log('点击分类:', category)
  activeThirdLevel.value = category.id
  // 如果有当前选中的品牌，加载该品牌和该分类下的商品
  if (currentBrands.value.length > 0) {
    await fetchProducts(currentBrands.value[0].id, category.id)
  } else {
    // 没有选中品牌，仅根据分类查询商品
    await fetchProducts(null, category.id)
  }
}
const router = useRouter()
// 点击商品
// 修改 handleProductClick 方法
const handleProductClick = (product) => {
  console.log('点击商品:', product.productId)
  router.push({
    path: '/productDetail',
    name: 'productDetail',
    params: { productId: product.productId }
  })
}


// 初始化加载
onMounted(() => {
  fetchFirstLevelCategories()
})
</script>

<style scoped>
/* 样式部分保持不变 */
.category-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.category-header {
  padding: 10px 0;
  border-bottom: 2px solid #e1251b;
  margin-bottom: 20px;
}

.category-header h2 {
  margin: 0;
  font-size: 22px;
  color: #e1251b;
}

.category-main {
  display: flex;
  min-height: 400px;
}

.first-level {
  width: 200px;
  border-right: 1px solid #f0f0f0;
}

.first-level ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.first-level li {
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.first-level li:hover {
  background-color: #f5f5f5;
  color: #e1251b;
}

.first-level li.active {
  background-color: #e1251b;
  color: white;
}

.second-level {
  width: 250px;
  border-right: 1px solid #f0f0f0;
  padding: 0 10px;
  overflow-y: auto;
}

.second-level h3 {
  margin: 15px 0 10px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
  color: #333;
  font-size: 16px;
}

.brand-section {
  margin-bottom: 20px;
}

.brand-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin-bottom: 15px;
}

.brand-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.brand-item:hover {
  background-color: #f5f5f5;
}

.brand-logo {
  width: 60px;
  height: 30px;
  margin-bottom: 5px;
}

.brand-name {
  font-size: 12px;
  text-align: center;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}

.second-level ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.second-level li {
  padding: 12px 15px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}

.second-level li:hover {
  background-color: #f5f5f5;
  color: #e1251b;
}

.second-level li.active {
  background-color: #f0f0f0;
  color: #e1251b;
  font-weight: bold;
}

.dropdown-icon {
  transition: transform 0.3s;
}

.dropdown-icon.rotated {
  transform: rotate(180deg);
}

/* 右侧内容区域样式 */
.right-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.third-level {
  padding: 0 20px;
}

.third-level h3 {
  margin: 15px 0 20px;
  color: #333;
  font-size: 16px;
}

.third-level-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 15px;
}

.third-level .el-link {
  display: block;
  padding: 8px 12px;
  font-size: 14px;
  color: #666;
  border-radius: 4px;
  transition: all 0.3s;
  text-align: center;
}

.third-level .el-link:hover {
  color: #e1251b;
  background-color: #f5f5f5;
}

/* 商品展示区域样式 */
.product-section {
  flex: 1;
  padding: 0 20px;
  margin-top: 20px;
}

.product-section h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.product-grid {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.product-row {
  display: flex;
  gap: 20px;
}

.product-item {
  flex: 1;
  cursor: pointer;
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s;
}

.product-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.product-image {
  width: 100%;
  height: 160px;
  background-color: #f5f5f5;
}

.product-info {
  padding: 10px;
}

.product-name {
  font-size: 14px;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  font-size: 16px;
  color: #e1251b;
  font-weight: bold;
}

.empty-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  min-height: 200px;
  color: #999;
}
</style>
